import * as XLSX from 'xlsx';
import { flattenTreeData } from './treeUtils';

/**
 * 导出excel表格
 * @param data 树形数据
 * @param fileName 文件名
 * @param options 自定义配置项
 */
export function exportTreeToExcel(
    treeData: any[], 
    fileName: string, 
    options:{ 
        childrenKey?: string,
        columns?: {
            key: string
            title: string
            formatter?: (value: any, row: any) => any
        }[],
        indentSymbol?: string, //缩进符号
    } = {}
){
    const {
        childrenKey = 'children',
        columns,
        indentSymbol = ' ',
    } = options;
    //展平数据
    const flatData = flattenTreeData(treeData, childrenKey)
    //
    const exportData = flatData.map(item => {
        const row: Record<string, any> = {}
        if(columns){
            columns.forEach(col => {
                if(col.key === 'name' || col.key === 'title'){
                    row[col.title] = indentSymbol.repeat(item._level) 
                    + (col.formatter ? col.formatter(item[col.key], item): item[col.key])
                }else{
                    row[col.title] = col.formatter ? col.formatter(item[col.key], item) : item[col.key]
                }
            })
        }else{
            //处理缩进
            Object.keys(item).forEach(key => {
                if(key !== '_level' && key !== '_parentPath'){
                    //
                    if(key === 'name' || key === 'title'){
                        row[key] = indentSymbol.repeat(item._level) + item[key]
                    }else{
                        row[key] = item[key]
                    }
                }
            })
        }
        return row;
    })
    const wb = XLSX.utils.book_new()
    const ws = XLSX.utils.json_to_sheet(exportData)
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
    XLSX.writeFile(wb, `${fileName}.xlsx`)
}